from client import es_client
from client.redis_client import r
from model.wristband_models import HealthData
from service.battery import get_intensity_redis
from utils.data_operation_util import deduplicate_dict_list
from utils.logger_util import logger
from utils.date_utils import timestamp_to_str_000z


async def save_all_health(health_data: HealthData, data_authority: dict, intensity_dict: dict):
    create_date = timestamp_to_str_000z(health_data.timestamp)
    imei = health_data.device_id
    intensity = intensity_dict['intensity']
    health_es_data = []
    if health_data.blood_pressure_high > 0:
        blood_pressure_data = {
            'bloodPressureHigh': health_data.blood_pressure_high,
            'bloodPressureLow': health_data.blood_pressure_low,
            'createDate': create_date,
            'dataType': '血压',
            'imei': imei,
            'intensity': intensity_dict['intensity'],
            'step_8_min': intensity_dict['step'],
            'dataAuthority': data_authority
        }
        s = health_data.blood_pressure_high
        d = health_data.blood_pressure_low
        if s >= 140 or d >= 90:
            blood_pressure_data['exception_level'] = 1
        if s >= 160 or d >= 100:
            blood_pressure_data['exception_level'] = 2
        if s >= 180 or d >= 120:
            blood_pressure_data['exception_level'] = 3
        health_es_data.append(blood_pressure_data)
    if health_data.heart_rate > 0:
        heart_rate_data = {
            'createDate': create_date,
            'dataType': '心率',
            'imei': health_data.device_id,
            'healthValue': health_data.heart_rate,
            'intensity': intensity_dict['intensity'],
            'step_8_min': intensity_dict['step'],
            'dataAuthority': data_authority
        }
        heart_rate = health_data.heart_rate
        if 50 <= heart_rate <= 59 or 101 <= heart_rate <= 110:
            heart_rate_data['exception_level'] = 1
        elif 40 <= heart_rate <= 49 or 111 <= heart_rate <= 130:
            if 111 <= heart_rate <= 130:
                if intensity < 2:
                    heart_rate_data['exception_level'] = 2
            else:
                heart_rate_data['exception_level'] = 2
        elif heart_rate < 40 or heart_rate > 130:
            if heart_rate > 130:
                if intensity < 3:
                    heart_rate_data['exception_level'] = 3
            else:
                heart_rate_data['exception_level'] = 3
        health_es_data.append(heart_rate_data)

    if health_data.blood_oxygen > 0:
        blood_oxygen_data = {
            'createDate': create_date,
            'dataType': '血氧',
            'imei': health_data.device_id,
            'healthValue': health_data.blood_oxygen,
            'dataAuthority': data_authority,
            'intensity': intensity_dict['intensity'],
            'step_8_min': intensity_dict['step']
        }
        blood_oxygen = health_data.blood_oxygen
        if 90 <= blood_oxygen <= 94:
            blood_oxygen_data['exception_level'] = 1
        elif 85 <= blood_oxygen <= 89:
            blood_oxygen_data['exception_level'] = 2
        elif blood_oxygen < 85:
            blood_oxygen_data['exception_level'] = 3
        health_es_data.append(blood_oxygen_data)

    if health_data.body_temperature > 0:
        body_temperature_data = {
            'createDate': create_date,
            'dataType': '体温',
            'imei': health_data.device_id,
            'healthValue': float(health_data.body_temperature),
            'dataAuthority': data_authority,
            'intensity': intensity_dict['intensity'],
            'step_8_min': intensity_dict['step']
        }
        body_temperature = float(health_data.body_temperature)
        if 37.3 <= body_temperature <= 37.8 or 35 <= body_temperature <= 35.5:
            body_temperature_data['exception_level'] = 1
        elif 37.9 <= body_temperature <= 38.5 or 34 <= body_temperature <= 34.9:
            body_temperature_data['exception_level'] = 2
        elif body_temperature > 40 or body_temperature < 34:
            body_temperature_data['exception_level'] = 3
        health_es_data.append(body_temperature_data)
    es = await es_client.get_es_client()
    await es.bulk('p_health_logs', health_es_data)
    logger.info(f'批量存入健康日志{health_es_data}')


async def find_health_log_dao(data: dict):
    query = {
        "size": 1000,
        "query": {
            "bool": {
                "must": [
                    {"terms": {"imei": data['imei']}},
                    {"range": {
                        "createDate": {
                            "gte": data['startDate'],
                            "lte": data['endDate']
                        }
                    }}
                ]
            }
        },
        "sort": [{"createDate": {"order": "asc"}}]
    }
    if data.get('type') is not None and data['type'] != '':
        query['query']['bool']['must'].append(
            {"term": {"dataType": data.get('type')}}
        )

    es = await es_client.get_es_client()
    result = await es.search_documents('p_health_logs', query=query)
    deduplicate_list = deduplicate_dict_list(result, {'imei', 'createDate', 'dataType'})
    return deduplicate_list


async def find_health_exception_imei(data: dict, depart: list):
    query = {
        "size": 0,
        "query": {
            "bool": {
                "must": [
                    {"range": {
                        "createDate": {
                            "gte": data['startDate'],
                            "lte": data['endDate']
                        }
                    }},
                    {"range": {
                        "exception_level": {
                            "gte": data['level']
                        }
                    }}
                ]
            }
        }
    }
    agg_list = data['agg_list']
    aggs = {
        "field1": {
            "terms": {
                "field": agg_list[0],
            }
        }
    }
    if len(agg_list) > 1:
        aggs['field1']['aggs'] = {
            "field2": {
                "terms": {
                    "field": agg_list[1],
                }
            }
        }
    query['aggs'] = aggs
    if depart[0] != 0 or len(depart) > 1:
        query['query']['bool']['must'].append({"terms": {"dataAuthority.depart": depart}})
    es = await es_client.get_es_client()
    result = await es.search('p_health_logs', query=query)
    return result['aggregations']['field1']['buckets']



